import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import type { ActionReducerMapBuilder, AsyncThunk, PayloadAction } from "@reduxjs/toolkit";
import type { AsyncThunkConfig } from "@reduxjs/toolkit/dist/createAsyncThunk";
import type { Category } from "@/type/CategoryType";
import { fetchCategoryListAPI } from "@/api/categoryAPI";


type InitialState = {
   categoryList: Category[]
}

const initialState: InitialState = {
   categoryList: [],
};

/**
 * @description 获取分类列表的asyncThunk函数
 * */
export const fetchCategoryListThunk: AsyncThunk<Category[], void, AsyncThunkConfig> = createAsyncThunk("fetchCategoryListThunk", async (_: void, { rejectWithValue }) => {
   try {
      const { data: { list } } = await fetchCategoryListAPI();
      return list;
   } catch (error: any) {
      return rejectWithValue(error.message);
   }
});


const homeStore = createSlice({
   name: "homeStore",
   initialState,
   reducers: {},
   extraReducers(builder: ActionReducerMapBuilder<InitialState>) {
      builder.addCase(fetchCategoryListThunk.fulfilled, (state: InitialState, action: PayloadAction<Category[]>) => {
         state.categoryList = action.payload;
      });
   },

});


export default homeStore.reducer;
